<template>
  <el-dialog v-model="dialogVisible" width="100%" style="height: 3.8rem;" :before-close="HandleClose" class="dialog-wrap customWidth">
    <div style="display: flex;justify-content: center;align-items: center;height: .3rem">
      <!--<img src="" alt="">-->
      <div class="ksss">快速上手</div>
    </div>
    <div style="height: calc(100% - .7rem); margin-top: .01rem; margin-bottom: 0.1rem;">
      <el-container style="height: 100%;overflow: auto">
        <el-aside style="padding:.05rem;background-color: #f4f6f8;height: 100% ">
          <div class="content-left">
            <img class="Img" src="@/assets/images/icon_sortc.png" />
            <span style="font-size: .1rem;margin-left: .01rem;margin-right: .05rem">指标大类</span>
            <el-popover placement="right" :width="550" trigger="click" :visible="visible">
              <template #reference>
                <el-icon size=".12rem" color="#5C7CFF" @click="showSearch" class="el-icon-wrap"><Search /></el-icon>
              </template>
              <div style="max-height: 2rem;overflow: auto">
                <div style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 5px">
                  <el-popover placement="bottom" :width="450" trigger="click" :visible="visible&&autocompleteData.records&&autocompleteData.records.length>0">
                    <template #reference>
                      <el-input
                          placeholder=""
                          v-model="params.indicatorName"
                          ref="autoCompleteRef"
                          @input="querySearch"
                      >
                        <template #append>
                          <el-icon @click="visible=false" size=".12rem" color="#5C7CFF" class="el-icon-wrap"><Close /></el-icon>
                        </template>
                        <template #prepend>
                          <el-icon @click="searchFun" size=".12rem" color="#5C7CFF" class="el-icon-wrap"><Search /></el-icon>
                        </template>
                      </el-input>
                    </template>
                    <div class="infinite-list-wrapper" style="overflow: auto" v-if="autocompleteData.records&&autocompleteData.records.length>0">
                      <ul
                          v-infinite-scroll="querySearchLoad"
                          infinite-scroll-distance="10"
                          class="list"
                          :infinite-scroll-disabled="disabled">
                        <li v-for="item in autocompleteData.records"
                            :key="item.id"
                            class="list-item"
                            @click="getIndicator(item)">{{ item.indicatorName }}</li>
                      </ul>
                      <p v-if="loadingScroll">加载中...</p>
                      <p v-if="noMore">没有更多了...</p>
                    </div>
                  </el-popover>
                </div>
                <el-table
                    v-if="gridData.length>0"
                    :data="gridData"
                    stripe
                    border
                    :header-cell-style="{background:'#F5F7FA',color:'#333333'}">
                  <el-table-column width="200" prop="" label="指标名称">
                    <template #default="scope">
                      <div style="cursor: pointer" @click="toDetail(scope.row)" class="ellipsis-wrap">{{scope.row.indicatorName}}</div>
                    </template>
                  </el-table-column>
                  <el-table-column property="" label="数据表">
                    <template #default="scope">
                      <div style="cursor: pointer" @click="toDetail(scope.row)">
                        <span>{{scope.row.tittle}}</span>
                        <span v-if="scope.row.tableName">({{scope.row.tableName}})</span>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-popover>
          </div>
          <el-tree ref="tree_ref"
                   v-loading="loading"
                   :data="menuList"
                   :props="defaultProps"
                   highlight-current
                   :default-expanded-keys="expandedKeys"
                   :current-node-key="expandedKeys[0]"
                   node-key="id"
                   :accordion="true"
                   style="display: inline-block; min-width: 100%;padding: 10px"
                   @node-click="handleNodeClick">
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <div style="display: flex;">
                  {{ node.label }}
                  <span>({{data.indicatorNum}})</span>
                  <div v-if="data.maxPeriod&&data.tableName">
                    <span style="color: #fb4222;margin-left: 5px;font-size: 12px">{{data.maxPeriod}}</span>
                    <i class="iconfont icon-hot"></i>
                  </div>
                </div>
              </div>
            </template>
          </el-tree>
        </el-aside>

        <el-container style="background-color: #f4f6f8;padding:0.05rem;margin-left: 0.05rem;">
          <div class="content-right">
            <div class="content-left">
              <img class="Img" src="@/assets/images/icon_bq.png" />
              <span style="font-size: .1rem;margin-left: .01rem;" v-html="routeDetail"></span>
            </div>
            <div class="demo-collapse">
              <el-collapse accordion v-model="activeCollapseItem" @change="handleChange">
                <el-collapse-item v-for="(item, index) in content" :key="index" :name="index" :class="item.isQuickq=='1'?'':'collapse-arrow-none'">
                  <template #title>
                    <div style="display: flex;align-items: center;padding: 0 10px" @click="stopProp">
                      <img src="@/assets/images/suspension/zhibiao.png" style="width: 15px;height: 15px;margin-right: 5px"/>
                      <div
                          style="user-select: all;display: flex;height: 0.1rem;align-items: center;line-height: .15rem;"
                          @click="copyText(item.indicatorName)">{{ item.indicatorName }}</div>
                    </div>
                  </template>
                  <div v-if="activeCollapseItem==index&&item.isQuickq=='1'" style="display: flex;flex-wrap: wrap;align-items: center;padding: 0 10px">
                    <el-date-picker
                        v-if="item.dateType=='month'"
                        v-model="item.maxPeriod"
                        format="YYYYMM"
                        value-format="YYYYMM"
                        type="month"
                        placeholder="选择日期"
                        @change="changeFun"
                        style="width: 150px;"
                        :disabled-date="item.disabledDate"
                    />
                    <!-- 日期 -->
                    <el-date-picker
                        v-else
                        v-model="item.maxPeriod"
                        type="date"
                        placeholder="选择日期"
                        format="YYYYMMDD"
                        value-format="YYYYMMDD"
                        style="width: 150px;"
                        :disabled-date="item.disabledDate"
                    >
                    </el-date-picker>
                    <el-select
                        filterable
                        v-model="item.latnName"
                        remote
                        reserve-keyword
                        remote-show-suffix
                        placeholder="请选择"
                        style="color: #000"
                    >
                      <el-option
                          v-for="(itemOp, index) in current_lant_id_option"
                          :key="index"
                          :label="itemOp.label"
                          :value="itemOp.label"
                      >
                      </el-option>
                    </el-select>
                    <span v-if="latitudeList.length>0" v-for="itemLat in latitudeList">
                      <el-select
                          filterable
                          v-model="itemLat.latitudeValue"
                          remote
                          clearable
                          reserve-keyword
                          remote-show-suffix
                          placeholder="请选择"
                          style="color: #000"
                      >
                      <el-option
                          v-for="(itemOp, index) in itemLat.metaDataModels"
                          :key="index"
                          :label="itemOp.itemName"
                          :value="itemOp.itemName"
                      >
                      </el-option>
                    </el-select>
                    </span>
                    <span style="margin-left: .05rem">的</span>
                    <span style="color:#3ccefa;margin-left: .05rem;margin-right: .05rem">{{ item.indicatorName }}</span><span>是多少？</span>
                    <el-button size="small" type="primary" @click="getQu(item.latnName,item.maxPeriod,item.indicatorName)">快速提问</el-button>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </el-container>
      </el-container>
    </div>
    <div class="dialog-footer" style="text-align: center;height: .4rem">
      <el-button type="primary" @click="dialogVisible = false" round style="width: .8rem;height: .2rem;font-size: .1rem">确 定</el-button>
      <el-button @click="visible = false;dialogVisible = false" round style="width: .8rem;height: .2rem;font-size: .1rem">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { commonCopyText } from '@/common/util'
import { getDialogData,
  getIndicator,
  getUserFuzzyIndicatorList,
  getIndicatorListByIndicatorName,
  getIndicatorById,
  getUserIndiDirList,
  getVisibleLatitudeList} from '@/api/chartdb'
import consts from '../../common/consts'
import { Search } from '@element-plus/icons-vue'

export default {
  components: {
    Search,
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      index: '',
      menuList: [],
      list: [],
      content: [],
      selectItem:{},
      activeCollapseItem:'',
      routeDetail:"具体指标",
      lant_id_option:consts.lant_id_option,
      current_lant_id_option:[],
      gridData:[],
      params:{
        indicatorName:'',
        tableCode:'',
      },
      defaultProps:{
        children: 'children',
        label: 'title',
        id:'id',
        isLeaf: 'leaf'
      },
      autocompleteData:{
        records:[]
      },
      expandedKeys:[],
      visible:false,
      fuzzyParams:{
        keyword:"",
        startIndex:1,
        pageSize:10
      },
      disabled:false,
      noMore:false,
      loadingScroll:false,
      currentTable:'',
      latitudeList:[]
    }
  },
  // 生命周期
  mounted() {
    if(localStorage.getItem("lantId")=="888"){
      this.current_lant_id_option=this.lant_id_option
    }else {
      const op=this.lant_id_option.find(item=>{return item.value==localStorage.getItem("lantId")})
      this.current_lant_id_option.push(op)
    }
  },
  methods: {
    copyText(msg) {
      commonCopyText(msg)
    },
    stopProp: function (e) {
      e.stopPropagation()
    },
    showSearch(){
      this.params.indicatorName='';
      this.gridData=[];
      this.visible=true;
      this.$refs.autoCompleteRef.focus()
      this.$nextTick(()=>{
        this.querySearch()
      })
    },
    toDetail(row){
      this.visible = false
      this.expandedKeys=[]
      this.expandedKeys.push(row.indiDirParentId)
      this.$refs['tree_ref'].setCurrentKey(row.indiDirParentId)
      getIndicatorById({ id:row.id,tableName:row.tableName,period:row.period }).then((res) => {
        this.content=[];
        let item=res.data.data
        if(item.isVisible!="0"){
          item.dateType="day"
          var startTime="";
          var endTime="";
          item.minPeriod=item.minPeriod+""
          item.maxPeriod=item.maxPeriod+""
          var startDate=item.minPeriod
          var endDate=item.maxPeriod
          let latnName="";
          if(this.current_lant_id_option.length>0){
            item.latnName=this.current_lant_id_option[0].label
          }
          if(item.maxPeriod.toString().length==6){
            item.dateType="month"
            const year1 = parseInt(startDate.substr(0, 4), 10);
            const month1 = parseInt(startDate.substr(4, 2), 10) - 1;
            const year2 = parseInt(endDate.substr(0, 4), 10);
            const month2 = parseInt(endDate.substr(4, 2), 10) - 1;
            startTime=new Date(year1, month1);
            endTime=new Date(year2, month2);
          }else if(item.maxPeriod.toString().length==8){
            const year1 = parseInt(startDate.substr(0, 4), 10);
            const month1 = parseInt(startDate.substr(4, 2), 10) - 1;
            const day1 = parseInt(startDate.substr(6, 2), 10);
            const year2 = parseInt(endDate.substr(0, 4), 10);
            const month2 = parseInt(endDate.substr(4, 2), 10) - 1;
            const day2 = parseInt(endDate.substr(6, 2), 10);
            startTime=new Date(year1, month1, day1);
            endTime=new Date(year2, month2, day2);
          }
          item.disabledDate=(time) => {
            if(!endTime||!startTime){
              return ""
            }else {
              return time.getTime() > endTime.getTime()||time.getTime() < startTime.getTime()
            }
          }
          this.content.push(item)
        }
      })
    },
    getIndicator(item){
      this.params.indicatorName=item.indicatorName
      this.params.tableCode=item.tableCode
      this.autocompleteData={
        records:[]
      }
      this.searchFun()
    },
    searchFun(){
      getIndicatorListByIndicatorName({ indicatorName:this.params.indicatorName,tableCode:this.params.tableCode }).then((res) => {
        this.gridData=res.data.data.data
      })
    },
    querySearch(queryString) {
      this.loadingScroll=true
      this.autocompleteData={}
      if(!queryString) queryString=""
      let keywords=queryString.split(" ").join(",");
      this.fuzzyParams.keyword=keywords
      this.fuzzyParams.startIndex=1
      getUserFuzzyIndicatorList(this.fuzzyParams).then((res) => {
        // let autocompleteList=res.data.data;
        // cb(autocompleteList);
        this.autocompleteData=res.data.data;
        if(this.autocompleteData.records.length>=this.autocompleteData.total){
          this.noMore=true
          this.disabled=true
        }else {
          this.noMore=false
          this.disabled=false
        }
        this.loadingScroll=false
      })
    },
    querySearchLoad() {
      this.disabled=true
      this.loadingScroll=true
      this.fuzzyParams.startIndex+=1
      if(this.autocompleteData.records.length>=this.autocompleteData.total){
        this.noMore=true
        this.disabled=true
        this.loadingScroll=false
        return false
      }else {
        this.noMore=false
      }
      setTimeout(() => {
        getUserFuzzyIndicatorList(this.fuzzyParams).then((res) => {
            this.autocompleteData.records.push(...res.data.data.records);
            this.loadingScroll=false
            this.disabled=false
        })
      }, 1500)
    },
    handleChange(val){
      this.activeCollapseItem=val
      this.latitudeList.forEach(item=>{
        item.latitudeValue=""
      })
    },
    getQu(latnName,maxPeriod,indicatorName){
      const year = parseInt(maxPeriod.substr(0, 4), 10);
      const month = parseInt(maxPeriod.substr(4, 2), 10);
      let day="";
      var qu=year+"年"+month+"月"
      if(maxPeriod.toString().length==8) {
        let day = parseInt(maxPeriod.substr(6, 2), 10);
        qu+=day+"日"
      }
      this.dialogVisible = false
      if(day){
        qu+=day+"日"
      }
      qu+=latnName
      this.latitudeList.forEach(item=>{
        if(item.latitudeValue){
          qu+=item.latitudeValue
        }
      })
      qu+="的"+indicatorName+"是多少？"
      this.$emit("newQu",qu)
    },
    changeFun(e){},
    handleDialog(param) {
      console.log("param=========>",param)
      this.dialogVisible = true;
      if(this.menuList.length==0||param) {
        this.loading=true
        getUserIndiDirList({}).then((res) => {
          this.menuList = res.data.data.data
          this.menuList.sort(this.menuSortMethod)
          this.loading=false
          if(param){
            this.$nextTick(()=>{
              this.expandedKeys=[]
              this.expandedKeys.push(param)
              // this.$refs['tree_ref'].setCurrentKey(this.expandedKeys)
            })
          }
        })
      }else {
        this.expandedKeys=[]
        // this.$refs['tree_ref'].setCurrentKey([])
      }
    },
    menuSortMethod(a,b){
      if(a.menuSort < b.menuSort) {
        return -1; // a在b之前
      } else if(a.menuSort > b.menuSort) {
        return 1; // a在b之后
      } else {
        return 0; // 相等
      }
    },
    openDialog() {
      this.dialogVisible = true; // 打开弹窗
    },
    HandleClose(done) {
      this.visible = false; // 关闭
      this.dialogVisible = false; // 关闭
    },
    getRouteDetail(node){
      if(node&&node.label){
        if(this.routeDetail){
          this.routeDetail=`${node.label}<span style='color: #5C7CFF'> > </span>${this.routeDetail}`
        }else {
          this.routeDetail=`${node.label}`
        }
        if(node.parent){
          this.getRouteDetail(node.parent)
        }
      }
    },
    handleNodeClick(e, node) {
      this.routeDetail="";
      this.getRouteDetail(node);
      if (!(node.data.children && node.data.children.length > 0)) {
        this.latitudeList=[]
        this.getTable(node)
        this.activeCollapseItem=""
        //获取指标
        getIndicator(node.data.menuId).then((res) => {
          // this.content = res.data.data
          this.content=[];
          res.data.data.forEach((item,index)=>{
            if(item.isVisible!="0"){
              if(this.current_lant_id_option.length>0){
                item.latnName=this.current_lant_id_option[0].label
              }
              item.maxPeriod=node.data.maxPeriod+""
              item.minPeriod=node.data.minPeriod+""
              item.dateType="day"
              var startTime="";
              var endTime="";
              var startDate=item.minPeriod
              var endDate=item.maxPeriod
              if(item.maxPeriod.toString().length==6){
                item.dateType="month"
                const year1 = parseInt(startDate.substr(0, 4), 10);
                const month1 = parseInt(startDate.substr(4, 2), 10) - 1;
                const year2 = parseInt(endDate.substr(0, 4), 10);
                const month2 = parseInt(endDate.substr(4, 2), 10) - 1;
                startTime=new Date(year1, month1);
                endTime=new Date(year2, month2);
              }else if(item.maxPeriod.toString().length==8){
                const year1 = parseInt(startDate.substr(0, 4), 10);
                const month1 = parseInt(startDate.substr(4, 2), 10) - 1;
                const day1 = parseInt(startDate.substr(6, 2), 10);
                const year2 = parseInt(endDate.substr(0, 4), 10);
                const month2 = parseInt(endDate.substr(4, 2), 10) - 1;
                const day2 = parseInt(endDate.substr(6, 2), 10);
                startTime=new Date(year1, month1, day1);
                endTime=new Date(year2, month2, day2);
              }
              item.disabledDate=(time) => {
                if(!endTime||!startTime){
                  return ""
                }else {
                  return time.getTime() > endTime.getTime()||time.getTime() < startTime.getTime()
                }
              }
              this.content.push(item)
            }
          })
        })
        //获取维度
        getVisibleLatitudeList({ tableCode:this.currentTable }).then((res) => {
          this.latitudeList=res.data.data
          // this.latitudeList.forEach(item=>{
          //   item.latitudeValue=item.metaDataModels[0].itemName
          // })
        })
      }else {
        this.content=[]
      }
    },
    //查询当前节点对应的数据表
    getTable(node){
      this.currentTable=""
      if(node){
        if(node.data.tableName){
          this.currentTable=node.data.tableName
        }else {
          this.getTable(node.parent)
        }
      }
    }
  },
}
</script>

<style scoped>
.choicebq {
  border: 1px solid #dcdcdc;
  border-radius: 14px;
  text-align: left;
  margin: 8px 0px;
  padding: 8px 15px;
  background-color: #fff;
  cursor: pointer;
}

.el-menu-item-group__title {
  margin: -7px 0 -7px -20px;
}

.content-left {
  height: 30px;
  color: black;
  /*display: inline-block;*/
  display: flex;
  align-items: center;
  margin-bottom: .05rem;
}

.content-right {
  width: 100%;
  height: 100%;
  color: black;
  display: inline-block;
  white-space: normal;
  /* 设置文本自动换行 */
  word-break: break-all;
  /* 允许单词被强制换行 */
  overflow: auto;
  /* 设置溢出时显示滚动条 */
}

.content-right-input {
  margin-left: 280px;
  display: inline-block
}

.container-header {
  margin-bottom: 10px;
}

.title1 {
  width: 310px;
  height: 46px;
  background: #fff;
  border: 1px solid #d5d6d8;
  border-radius: 22px;
  display: inline-block;
  margin: 6px 5px;
  padding: 10px 15px;
}

.Img {
  vertical-align: text-bottom;

}
  .ksss{
    color: aliceblue;font-size: 16px;
    width: 300px;
    height: 40px;
    background: url("@/assets/images/title_bg.png") no-repeat;
    background-size: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
:deep(.el-input__inner) {
  color: #333 !important;
  width: 60px;
}

::-webkit-scrollbar {
  width: 5px; /* 设置滚动条的宽度 */
  border-radius: 5px;
  background: #e2e2e2;
}
::-webkit-scrollbar-thumb {
  background: #C1C0C0FF; /* 设置滑块的背景颜色 */
  border-radius: 5px;
}

/* 设置滚动条滑块的hover样式 */
::-webkit-scrollbar-thumb:hover {
  background: #C1C0C0FF; /* 设置滑块的hover背景颜色 */
}
/*::-webkit-scrollbar-track {*/
/*  -webkit-box-shadow: inset 0 0 3px rgba(14, 32, 48, 0);*/
/*  border-radius: 5px;*/
/*  background-color: #eee;*/
/*  border: 1px solid #dcdcdc;*/
/*}*/
/*::-webkit-scrollbar {*/
/*  width: .2rem; !* 设置滚动条的宽度 *!*/
/*}*/
:deep(.collapse-arrow-none .el-collapse-item__arrow){
  display: none !important;
}
:deep(.collapse-arrow-none .el-collapse-item__content){
  padding: 0 !important;
}
.el-icon-wrap{
  cursor: pointer;
}
.ellipsis-wrap{
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.el-aside{
  width: 30% !important;
}
.infinite-list-wrapper {
  height: 300px;
  text-align: center;
}
.infinite-list-wrapper .list {
  padding: 0;
  margin: 0;
  list-style: none;
}

.infinite-list-wrapper .list-item {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  color: #666;
  cursor: pointer;
  height: 0.18rem;
  font-size: .08rem;
  padding-left: .1rem;
}
.infinite-list-wrapper .list-item:hover {
  background: #095EF7;
  color: #fff;
}
/*.infinite-list-wrapper .list-item + .list-item {*/
/*  margin-top: 10px;*/
/*}*/

</style>